@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>添加采购入库单</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <style>
        body { margin: 0; padding: 20px; background-color: #f5f5f5; }
        .form-container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            max-width: 800px;
            margin: 0 auto;
        }
        .form-title {
            text-align: center;
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 30px;
            color: #333;
        }
        .layui-form-label {
            width: 120px;
            padding: 9px 0;
        }
        .layui-input-block {
            margin-left: 140px;
        }
        .required {
            color: red;
            margin-right: 3px;
        }
        .auto-generate {
            background-color: #f8f8f8;
            cursor: not-allowed;
        }
        .form-buttons {
            text-align: center;
            margin-top: 30px;
        }
        .form-buttons .layui-btn {
            margin: 0 10px;
            padding: 9px 25px;
        }
        .supplier-select {
            position: relative;
        }
        .supplier-btn {
            position: absolute;
            right: 0;
            top: 0;
            border-left: 1px solid #e6e6e6;
            background: #f8f8f8;
            padding: 0 15px;
            height: 38px;
            line-height: 38px;
            cursor: pointer;
        }
        .supplier-btn:hover {
            background: #e6e6e6;
        }
        .layui-form-label.required:after {
            content: "*";
            color: red;
            position: absolute;
            margin-left: 4px;
        }
        
        /* 供应商选择表格样式 */
        #supplierSelectDialog .layui-table tr:hover {
            background-color: #e6f7ff;
        }
        #supplierSelectDialog .layui-table tr.layui-table-click {
            background-color: #bae7ff;
        }
        #supplierSelectDialog .layui-table {
            margin: 0;
        }
        #supplierSelectDialog .layui-table thead tr {
            background-color: #f8f9fa;
        }
    </style>
</head>
<body>
    <div class="form-container">
        <div class="form-title">添加采购入库单</div>
        
        <form class="layui-form" id="addForm" lay-filter="addForm">
            <div class="layui-row">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">
                            <span class="required">*</span>入库单编号
                        </label>
                        <div class="layui-input-block">
                            <input type="text" name="lnboundCode" placeholder="自动生成" class="layui-input auto-generate" readonly>
                            <div class="layui-form-mid layui-word-aux">
                                <input type="checkbox" name="autoGenerate" lay-skin="switch" lay-text="自动生成|手动输入" checked disabled>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">
                            <span class="required">*</span>入库单名称
                        </label>
                        <div class="layui-input-block">
                            <input type="text" name="lnboundName" placeholder="请输入入库单名称" class="layui-input" lay-verify="required">
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="layui-row">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">
                            <span class="required">*</span>入库日期
                        </label>
                        <div class="layui-input-block">
                            <input type="text" name="lnboundDate" placeholder="请选择入库日期" class="layui-input" id="lnboundDate" lay-verify="required">
                        </div>
                    </div>
                </div>
                
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">采购订单号</label>
                        <div class="layui-input-block">
                            <input type="text" name="procurementNumber" placeholder="请输入采购订单号" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="layui-row">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">
                            <span class="required">*</span>供应商
                        </label>
                        <div class="layui-input-block supplier-select">
                            <input type="text" name="vendorName" placeholder="请选择供应商" class="layui-input" lay-verify="required" readonly>
                            <span class="supplier-btn" onclick="selectSupplier()">
                                <i class="layui-icon layui-icon-search"></i>
                            </span>
                        </div>
                    </div>
                </div>
                
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">单据状态</label>
                        <div class="layui-input-block">
                            <select name="documentStatus" lay-verify="">
                                <option value="">请选择</option>
                                <option value="草稿" selected>草稿</option>
                                <option value="待审核">待审核</option>
                                <option value="已完成">已完成</option>
                                <option value="已取消">已取消</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="layui-row">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">入库仓库</label>
                        <div class="layui-input-block">
                            <select name="warehouse" lay-verify="">
                                <option value="">请选择</option>
                                <option value="原料仓">原料仓</option>
                                <option value="成品仓">成品仓</option>
                                <option value="半成品仓">半成品仓</option>
                                <option value="备件仓">备件仓</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">总金额</label>
                        <div class="layui-input-block">
                            <input type="number" name="totalAmount" placeholder="请输入总金额" class="layui-input" step="0.01">
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea name="remark" placeholder="请输入备注" class="layui-textarea" rows="3"></textarea>
                </div>
            </div>
            
            <div class="form-buttons">
                <button type="submit" class="layui-btn" lay-submit lay-filter="saveBtn">保存</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="closeWindow()">取消</button>
            </div>
        </form>
    </div>

    <!-- 供应商选择弹窗 -->
    <div id="supplierSelectDialog" style="display: none; padding: 20px;">
        <!-- 搜索条件 -->
        <div style="margin-bottom: 15px; padding: 15px; background: #f8f9fa; border-radius: 5px;">
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md4">
                    <input type="text" id="supplierKeyword" placeholder="请输入供应商名称/编码" class="layui-input" />
                </div>
                <div class="layui-col-md3">
                    <select id="supplierIsEnabled" class="layui-input">
                        <option value="">是否启用</option>
                        <option value="true">是</option>
                        <option value="false">否</option>
                    </select>
                </div>
                <div class="layui-col-md3">
                    <button type="button" class="layui-btn" onclick="searchSupplier()">搜索</button>
                    <button type="button" class="layui-btn layui-btn-primary" onclick="loadSupplierData(1)">重置</button>
                </div>
            </div>
        </div>
        
        <!-- 供应商表格 -->
        <div style="max-height: 400px; overflow-y: auto;">
            <table class="layui-table">
                <thead>
                    <tr>
                        <th width="50">选择</th>
                        <th>编码</th>
                        <th>名称</th>
                        <th>等级</th>
                        <th>评分</th>
                        <th>电话</th>
                        <th>是否启用</th>
                        <th>地址</th>
                        <th>备注</th>
                    </tr>
                </thead>
                <tbody id="supplierTableBody">
                    <!-- 数据通过JS渲染 -->
                </tbody>
            </table>
        </div>
        
        <!-- 分页 -->
        <div id="supplierPagination" style="text-align: center; margin: 15px 0;"></div>
        
        <!-- 操作按钮 -->
        <div style="text-align: center; margin-top: 20px;">
            <button type="button" class="layui-btn" onclick="confirmSupplierSelection()">确定选择</button>
            <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
        </div>
    </div>

    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script>
        layui.use(['form', 'laydate', 'layer'], function() {
            var form = layui.form;
            var laydate = layui.laydate;
            var layer = layui.layer;
            var $ = layui.$;

            // 初始化日期选择器
            laydate.render({
                elem: '#lnboundDate',
                value: new Date().toISOString().split('T')[0], // 默认今天
                type: 'date'
            });

            // 页面加载时生成入库单编号
            generateInboundCode();

            // 生成入库单编号
            function generateInboundCode() {
                $.get('/api/Procurementwarehousing/GenerateCode', function(res) {
                    if (res.success) {
                        $('input[name="lnboundCode"]').val(res.code);
                    } else {
                        layer.msg('生成编号失败：' + res.message);
                    }
                }).fail(function() {
                    // 如果生成失败，使用默认格式
                    var now = new Date();
                    var dateStr = now.getFullYear() + 
                                 String(now.getMonth() + 1).padStart(2, '0') + 
                                 String(now.getDate()).padStart(2, '0');
                    $('input[name="lnboundCode"]').val('R' + dateStr + '000001');
                });
            }

            // 提交表单
            form.on('submit(saveBtn)', function(data) {
                var formData = data.field;
                
                // 数据验证
                if (!formData.lnboundCode) {
                    layer.msg('入库单编号不能为空');
                    return false;
                }
                if (!formData.lnboundName) {
                    layer.msg('入库单名称不能为空');
                    return false;
                }
                if (!formData.vendorName) {
                    layer.msg('供应商不能为空');
                    return false;
                }
                if (!formData.lnboundDate) {
                    layer.msg('入库日期不能为空');
                    return false;
                }

                // 显示加载层
                var loadIndex = layer.load(1, {
                    shade: [0.1,'#fff']
                });

                // 提交数据
                $.ajax({
                    url: '/api/Procurementwarehousing/Create',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(res) {
                        layer.close(loadIndex);
                        if (res.success) {
                            layer.msg('保存成功', {
                                icon: 1,
                                time: 1500
                            }, function() {
                                // 成功后关闭弹窗
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            });
                        } else {
                            layer.msg('保存失败：' + (res.message || '未知错误'), {icon: 2});
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.close(loadIndex);
                        console.log('保存失败:', xhr.responseText);
                        layer.msg('网络异常，请稍后重试', {icon: 2});
                    }
                });
                
                return false; // 阻止表单跳转
            });

            // 重新渲染表单
            form.render();
        });

        // 选择供应商
        function selectSupplier() {
            // 首先加载供应商数据
            loadSupplierData();
            
            // 打开供应商选择弹窗
            layer.open({
                type: 1,
                title: '选择供应商',
                area: ['90%', '80%'],
                maxmin: true,
                content: $('#supplierSelectDialog'),
                success: function(layero, index) {
                    // 弹窗打开成功后的处理
                },
                end: function() {
                    // 关闭弹窗后的处理
                }
            });
        }

        // 加载供应商数据
        function loadSupplierData(page = 1, keyword = '', isEnabled = '') {
            $.ajax({
                url: '/Supplier/GetSupplierPagedList/GetSupplierPagedListAsync',
                type: 'GET',
                data: {
                    keyword: keyword,
                    isEnabled: isEnabled,
                    page: page,
                    pageSize: 10
                },
                dataType: 'json',
                success: function(res) {
                    console.log('供应商数据:', res);
                    if (res && res.data && Array.isArray(res.data)) {
                        renderSupplierTable(res.data);
                        renderSupplierPagination(res.total, page);
                    } else {
                        $('#supplierTableBody').html('<tr><td colspan="9" style="text-align:center;">暂无数据</td></tr>');
                    }
                },
                error: function(xhr, status, error) {
                    console.log('加载供应商失败:', error);
                    layer.msg('加载供应商数据失败', {icon: 2});
                    $('#supplierTableBody').html('<tr><td colspan="9" style="text-align:center;">加载失败</td></tr>');
                }
            });
        }

        // 渲染供应商表格
        function renderSupplierTable(data) {
            var html = '';
            if (data && data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    var isEnabledText = item.isNo === 1 ? '<span style="color: #52c41a;">是</span>' : '<span style="color: #ff4d4f;">否</span>';
                    html += '<tr data-supplier=\'' + JSON.stringify(item) + '\' style="cursor: pointer;" onclick="selectSupplierRow(this)">';
                    html += '<td><input type="radio" name="supplierRadio" value="' + item.id + '" /></td>';
                    html += '<td>' + (item.supplierCode || '') + '</td>';
                    html += '<td>' + (item.supplierName || '') + '</td>';
                    html += '<td>' + (item.supplierGrade || '') + '</td>';
                    html += '<td>' + (item.supplierScore || '') + '</td>';
                    html += '<td>' + (item.supplierPhone || '') + '</td>';
                    html += '<td>' + isEnabledText + '</td>';
                    html += '<td>' + (item.supplierAdress || '') + '</td>';
                    html += '<td>' + (item.context || '') + '</td>';
                    html += '</tr>';
                }
            } else {
                html = '<tr><td colspan="9" style="text-align:center;">暂无数据</td></tr>';
            }
            $('#supplierTableBody').html(html);
        }

        // 渲染供应商分页
        function renderSupplierPagination(total, currentPage) {
            var pageSize = 10;
            var pageCount = Math.ceil(total / pageSize);
            var html = '';
            if (pageCount > 1) {
                for (var i = 1; i <= pageCount; i++) {
                    if (i === currentPage) {
                        html += '<button type="button" class="layui-btn layui-btn-primary layui-btn-sm" disabled>' + i + '</button> ';
                    } else {
                        html += '<button type="button" class="layui-btn layui-btn-primary layui-btn-sm" onclick="loadSupplierData(' + i + ')">' + i + '</button> ';
                    }
                }
            }
            $('#supplierPagination').html(html);
        }

        // 选择供应商行
        var selectedSupplier = null;
        function selectSupplierRow(row) {
            // 移除其他行的选中状态
            $('#supplierTableBody tr').removeClass('layui-table-click');
            $(row).addClass('layui-table-click');
            
            // 选中单选框
            $(row).find('input[type="radio"]').prop('checked', true);
            
            // 保存选中的供应商
            selectedSupplier = JSON.parse($(row).attr('data-supplier'));
            console.log('选中供应商:', selectedSupplier);
        }

        // 确认选择供应商
        function confirmSupplierSelection() {
            if (!selectedSupplier) {
                layer.msg('请选择一个供应商', {icon: 2});
                return;
            }
            
            // 填充供应商信息到表单
            $('input[name="vendorName"]').val(selectedSupplier.supplierName);
            
            // 关闭弹窗
            layer.closeAll();
            
            layer.msg('供应商选择成功', {icon: 1});
        }

        // 供应商搜索
        function searchSupplier() {
            var keyword = $('#supplierKeyword').val();
            var isEnabled = $('#supplierIsEnabled').val();
            loadSupplierData(1, keyword, isEnabled);
        }

        // 关闭窗口
        function closeWindow() {
            if (window.parent && window.parent.layer) {
                window.parent.layer.closeAll();
            } else {
                window.close();
            }
        }


    </script>
</body>
</html> 